﻿using Dapper_Core.Common;
using Dapper_Core.DAL.Impl;
using Dapper_Core.Model;
using Dapper_Core.Table;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

namespace Dapper_Core.BLL.Impl
{
    public class WorkflowCommonBusiness
    {
        public static (bool isCheckman, bool resubmit, List<WorkflowTransition> actionList) GetWorkflowInfo(string taskId, string currentCheckMan)
        {
            try
            {
                bool isCheckman = false;
                bool resubmit = false;
                List<WorkflowTransition> actionList = new List<WorkflowTransition>();
                //获取当前正在处理的任务
                Expression<Func<V_WorkflowTask, bool>> workflowTaskExp = workflowTask => workflowTask.TaskId == taskId;
                List<V_WorkflowTask> workflowTaskList = new BaseRepository<V_WorkflowTask>().GetList(workflowTaskExp).ToList();
                if (workflowTaskList != null && workflowTaskList.Count > 0 && string.Equals(workflowTaskList[0].CheckPinyinCode, currentCheckMan, StringComparison.OrdinalIgnoreCase))
                {
                    V_WorkflowTask workflowTask = workflowTaskList[0];
                    isCheckman = true;
                    resubmit = workflowTask.WorkflowNodeCode.EndsWith("_ReSubmitted");
                    //获取FromCode对应的所有WorkflowTransition
                    Expression<Func<WorkflowTransition, bool>> workflowTransitionExp = workflowTransition => workflowTransition.WorkflowCode == workflowTask.WorkflowCode && workflowTransition.FromCode == workflowTask.WorkflowNodeCode && workflowTransition.IsDeleted == 0;
                    actionList = new BaseRepository<WorkflowTransition>().GetList(workflowTransitionExp).ToList();
                }
                return (isCheckman, resubmit, actionList);
            }
            catch (Exception ex)
            {
                NlogUtility.WriteError(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName, "获取流程信息失败", "taskId=" + taskId + "，currentCheckMan=" + currentCheckMan, ex, "DapperCore");
                return (false, false, new List<WorkflowTransition>());
            }
        }

        public static (bool success, string message) HandleSubmit(string applyId, string deptId, string deptType, string workflowCode, string currentCheckMan, string remarks, out WorkflowInstance workflowInstance, out WorkflowRecord workflowRecord, out List<WorkflowTask> nextWorkflowTaskList)
        {
            try
            {
                V_WorkflowTransition startTransition = new V_WorkflowTransitionBusiness().GetStartTransition(workflowCode);
                DateTime now = DateTime.Now;

                #region 构建WorkflowInstance
                workflowInstance = new WorkflowInstance();
                workflowInstance.Id = Guid.NewGuid().ToString();
                workflowInstance.WorkflowTypeId = applyId;
                workflowInstance.WorkflowCode = workflowCode;
                workflowInstance.WorkflowNodeCode = startTransition.ToCode;
                workflowInstance.State = "active";
                workflowInstance.IsDeleted = 0;
                workflowInstance.Creator = currentCheckMan;
                workflowInstance.CreateDate = now;
                workflowInstance.Remarks = "";
                #endregion

                nextWorkflowTaskList = new List<WorkflowTask>();
                #region 构建inactive状态的WorkflowTask
                WorkflowTask workflowTask = new WorkflowTask();
                workflowTask.TaskId = Guid.NewGuid().ToString();
                workflowTask.WorkflowInstanceId = workflowInstance.Id;
                workflowTask.WorkflowNodeCode = startTransition.FromCode;
                workflowTask.CheckPinyinCode = currentCheckMan;
                workflowTask.State = "inactive";
                workflowTask.IsDeleted = 0;
                workflowTask.Creator = currentCheckMan;
                workflowTask.CreateDate = now;
                workflowTask.Remarks = "";
                nextWorkflowTaskList.Add(workflowTask);
                #endregion

                #region 构建WorkflowRecord
                workflowRecord = new WorkflowRecord();
                workflowRecord.WorkflowRecordId = Guid.NewGuid().ToString();
                workflowRecord.WorkflowTaskId = workflowTask.TaskId;
                workflowRecord.WorkflowTransitionCode = startTransition.Code;
                workflowRecord.Approver = currentCheckMan;
                workflowRecord.ApprovedDate = now;
                workflowRecord.IsDeleted = 0;
                workflowRecord.Creator = currentCheckMan;
                workflowRecord.CreateDate = now;
                workflowRecord.Remarks = remarks;
                #endregion

                #region 构建active状态的WorkflowTask
                if (startTransition.ToNodeType == "normal")
                {
                    Expression<Func<WorkflowNode, bool>> exp = workflowNode => workflowNode.WorkFlowCode == workflowCode && workflowNode.WorkflowNodeCode == startTransition.ToCode;
                    List<WorkflowNode> workflowNodeList = new BaseRepository<WorkflowNode>().GetList(exp).ToList();
                    if (workflowNodeList == null || workflowNodeList.Count < 1 || string.IsNullOrEmpty(workflowNodeList[0].RoleCode))
                    {
                        return (false, "未获取到下一步的审批角色");
                    }
                    List<V_Sys_UserRole> userRoleList = new Sys_User_RoleBusiness().GetUsers(workflowNodeList[0].RoleCode, deptId, deptType, currentCheckMan);
                    if (userRoleList == null || userRoleList.Count < 1)
                    {
                        return (false, "未获取到下一步的审批人");
                    }
                    foreach (V_Sys_UserRole item in userRoleList)
                    {
                        WorkflowTask temp = new WorkflowTask();
                        temp.TaskId = Guid.NewGuid().ToString();
                        temp.WorkflowInstanceId = workflowInstance.Id;
                        temp.WorkflowNodeCode = startTransition.ToCode;
                        temp.CheckPinyinCode = item.PinyinCode;
                        temp.State = "active";
                        temp.IsDeleted = 0;
                        temp.Creator = currentCheckMan;
                        temp.CreateDate = now;
                        temp.Remarks = "";
                        nextWorkflowTaskList.Add(temp);
                    }
                }
                #endregion

                return (true, "提交成功");
            }
            catch (Exception ex)
            {
                NlogUtility.WriteError(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName, "申请提交失败", $"applyId={applyId}，deptId={deptId}，deptType={deptType}，workflowCode={workflowCode}，currentCheckMan={currentCheckMan}，remarks={remarks}", ex, "DapperCore");
                workflowInstance = null;
                workflowRecord = null;
                nextWorkflowTaskList = new List<WorkflowTask>();
                return (false, "提交失败，请联系管理员");
            }
        }

        public static (bool success, string message) HandleAudit(string taskId, string deptId, string deptType, string currentCheckMan, string action, string remarks, out WorkflowInstance workflowInstance, out WorkflowRecord workflowRecord, out List<WorkflowTask> nextWorkflowTaskList, out V_WorkflowTransition nextWorkflowTransition)
        {
            try
            {
                workflowInstance = new WorkflowInstance();
                workflowRecord = new WorkflowRecord();
                nextWorkflowTaskList = new List<WorkflowTask>();
                nextWorkflowTransition = new V_WorkflowTransition();
                DateTime now = DateTime.Now;

                #region 获取WorkflowTask
                Expression<Func<V_WorkflowTask, bool>> workflowTaskExp = a => a.TaskId == taskId;
                List<V_WorkflowTask> workflowTaskList = new BaseRepository<V_WorkflowTask>().GetList(workflowTaskExp).ToList();
                if (workflowTaskList == null || workflowTaskList.Count < 1)
                {
                    return (false, "未获取到相关任务信息，请联系管理员");
                }
                V_WorkflowTask tempWorkflowTask = workflowTaskList[0];
                #endregion

                #region 获取WorkflowInstance
                Expression<Func<WorkflowInstance, bool>> workflowInstanceExp = a => a.WorkflowTypeId == tempWorkflowTask.WorkflowTypeId;
                List<WorkflowInstance> workflowInstanceList = new BaseRepository<WorkflowInstance>().GetList(workflowInstanceExp).ToList();
                if (workflowInstanceList == null || workflowInstanceList.Count < 1)
                {
                    return (false, "未获取到相关流程信息，请联系管理员");
                }
                WorkflowInstance tempWorkflowInstance = workflowInstanceList[0];
                #endregion

                #region 构建V_WorkflowTransition
                List<V_WorkflowTransition> workflowTransitionList = new V_WorkflowTransitionBusiness().GetNextTransition(tempWorkflowInstance.WorkflowCode, tempWorkflowInstance.WorkflowNodeCode, action);
                if (workflowTransitionList == null || workflowTransitionList.Count < 1)
                {
                    return (false, "未获取到流程的下一步信息，请联系管理员");
                }
                V_WorkflowTransition tempWorkflowTransition = workflowTransitionList[0];
                nextWorkflowTransition = tempWorkflowTransition;
                #endregion

                #region 构建WorkflowRecord
                workflowRecord.WorkflowRecordId = Guid.NewGuid().ToString();
                workflowRecord.WorkflowTaskId = taskId;
                workflowRecord.WorkflowTransitionCode = tempWorkflowTransition.Code;
                workflowRecord.Approver = currentCheckMan;
                workflowRecord.ApprovedDate = now;
                workflowRecord.IsDeleted = 0;
                workflowRecord.Creator = currentCheckMan;
                workflowRecord.CreateDate = now;
                workflowRecord.Remarks = remarks;
                #endregion

                #region 构建active状态的WorkflowTask
                if (tempWorkflowTransition.ToNodeType == "normal")
                {
                    Expression<Func<WorkflowNode, bool>> exp = workflowNode => workflowNode.WorkFlowCode == tempWorkflowInstance.WorkflowCode && workflowNode.WorkflowNodeCode == tempWorkflowTransition.ToCode;
                    List<WorkflowNode> workflowNodeList = new BaseRepository<WorkflowNode>().GetList(exp).ToList();
                    if (workflowNodeList == null || workflowNodeList.Count < 1 || string.IsNullOrEmpty(workflowNodeList[0].RoleCode))
                    {
                        return (false, "未获取到下一步的审批角色");
                    }
                    List<V_Sys_UserRole> userRoleList = new Sys_User_RoleBusiness().GetUsers(workflowNodeList[0].RoleCode, deptId, deptType, tempWorkflowInstance.Creator);
                    if (userRoleList == null || userRoleList.Count < 1)
                    {
                        return (false, "未获取到下一步的审批人");
                    }
                    foreach (V_Sys_UserRole item in userRoleList)
                    {
                        WorkflowTask temp = new WorkflowTask();
                        temp.TaskId = Guid.NewGuid().ToString();
                        temp.WorkflowInstanceId = tempWorkflowInstance.Id;
                        temp.WorkflowNodeCode = tempWorkflowTransition.ToCode;
                        temp.CheckPinyinCode = item.PinyinCode;
                        temp.State = "active";
                        temp.IsDeleted = 0;
                        temp.Creator = currentCheckMan;
                        temp.CreateDate = now;
                        temp.Remarks = "";
                        nextWorkflowTaskList.Add(temp);
                    }
                }
                else if(tempWorkflowTransition.ToNodeType == "end")
                {
                    WorkflowTask temp = new WorkflowTask();
                    temp.TaskId = Guid.NewGuid().ToString();
                    temp.WorkflowInstanceId = tempWorkflowInstance.Id;
                    temp.WorkflowNodeCode = tempWorkflowTransition.ToCode;
                    temp.CheckPinyinCode = "";
                    temp.State = "inactive";
                    temp.IsDeleted = 0;
                    temp.Creator = currentCheckMan;
                    temp.CreateDate = now;
                    temp.Remarks = "";
                    nextWorkflowTaskList.Add(temp);
                }
                #endregion

                #region 构建WorkflowInstance
                tempWorkflowInstance.WorkflowNodeCode = tempWorkflowTransition.ToCode;
                tempWorkflowInstance.State = "active";
                if (tempWorkflowTransition.ToNodeType == "end")
                {
                    tempWorkflowInstance.State = "inactive";
                }
                workflowInstance = tempWorkflowInstance;
                #endregion

                return (true, "审批成功");
            }
            catch (Exception ex)
            {
                NlogUtility.WriteError(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName, "申请审批失败", $"taskId={taskId}，deptId={deptId}，deptType={deptType}，currentCheckMan={currentCheckMan}，action={action}，remarks={remarks}", ex, "DapperCore");
                workflowInstance = null;
                workflowRecord = null;
                nextWorkflowTaskList = new List<WorkflowTask>();
                nextWorkflowTransition = null;
                return (false, "审批失败，请联系管理员");
            }
        }
    }
}
